<?php 

namespace app\seller\event;

use app\common\model\Goods as GoodsModel;
use app\common\model\GoodsAttr;
use app\common\model\GoodsAttribute;
use app\common\model\Spec;
use app\common\model\SpecGoodsPrice;
use app\common\model\SpecItem;
use app\common\utils\JsonService;

class GoodsEvent{

    /*
    * 商品列表
    */
    public static function goodsList($params){

        $page = ! empty($params['page']) && $params['page'] >= 1 ? $params['page'] : 1;
        $where = [];
        if($goods_id = isset($params['goods_id'])){
                    $where[] = [['goods_id','=',$params['goods_id']]];
            }
            if($cat_id = isset($params['cat_id'])){
                    $where[] = [['cat_id','like',"%{$params['cat_id']}%"]];
            }

            if($goods_name = isset($params['goods_name'])){
                    $where[] = [['goods_name','like',"%{$params['goods_name']}%"]];
            }

            if($figure_nu = isset($params['figure_nu'])){
                $where[] = [['figure_nu','like',"%{$params['figure_nu']}%"]];
            }

            if($seller_id = isset($params['seller_id'])){
                $where[] = [['seller_id','like',"%{$params['seller_id']}%"]];
            }

            if($brand_id = isset($params['brand_id'])){
                    $where[] = [['brand_id','like',"%{$params['brand_id']}%"]];
            }
            if($store_count = isset($params['store_count'])){
                    $where[] = [['store_count','like',"%{$params['store_count']}%"]];
            }

            if($last_update = isset($params['last_update'])){
                    $where[] = [['last_update','like',"%{$params['last_update']}%"]];
            }


            if($suppliers_id = isset($params['suppliers_id'])){
                    $where[] = [['suppliers_id','like',"%{$params['suppliers_id']}%"]];
            }

            $condition = [
                'where' => $where,
                'order' => ['goods_id' => 'desc'],
                    'paginate' => [
                    'page' => $page,
                    'query' => $params,
                ],
            ];
        $goods = GoodsModel::getPageAll($condition);
        return $goods;
    }


    /*
    * 新增商品
    */
    public static function createGoods($data){
        //商品相册
        $photo_album = isset($data['photo_album'])?serialize($data['photo_album']):'';
        $data['photo_album'] = $photo_album;
        //商品规格
        $spec_item = isset($data['item'])?$data['item']:[];
        $attr = isset($data['attr'])?$data['attr']:[];

        if($data['is_on_sale'] == 1){
            $data['on_time'] = time();
        }else{
            $data['on_time'] = 0;
        }

        GoodsModel::beginTrans();
        try {
            $goodsRes = GoodsModel::create($data);
            //处理规格
            if(!empty($spec_item)){
                $spec = [];
                foreach($spec_item as $k=>$v){
                    $spec[] = [
                        'key' =>$k,
                        'key_name'=>$v['key_name'],
                        'price'=>$v['price'],
                        'store_count'=>$v['store_count'],
                        'sku'=>$v['sku'],
                        'goods_id'=>$goodsRes->goods_id,
                    ];
                }
                SpecGoodsPrice::setAll($spec);
            }
            //处理属性
            if(!empty($attr)){
                $goods_attr = [];
                foreach($attr as $k=>$v){
                    $goods_attr[] = [
                        'goods_id'=>$goodsRes->goods_id,
                        'attr_id'=>$k,
                        'attr_value'=>$v,
                        'attr_price'=>0,
                    ];
                }
                GoodsAttr::setAll($goods_attr);
            }
            GoodsModel::commitTrans();
        } catch (\Exception $ex) {
            GoodsModel::rollbackTrans();
            return JsonService::error($ex->getMessage());
        }
        return JsonService::success();
    }

    /*
    * 更新商品
    */
    public static function updateGoods($data){
        //商品相册
        $photo_album = isset($data['photo_album'])?serialize($data['photo_album']):'';
        $data['photo_album'] = $photo_album;

        if($data['is_on_sale'] == 1){
            $data['on_time'] = time();
        }else{
            $data['on_time'] = 0;
        }

        //如果没有规格属性则把原来的规格数据删除
        if($data['goods_type'] == 0){
            GoodsAttr::delByWhere(['goods_id'=>$data['goods_id']]);
            SpecGoodsPrice::delByWhere(['goods_id'=>$data['goods_id']]);
        }
        //print_r($data);die();
        //商品规格
        $spec_item = isset($data['item'])?$data['item']:[];
        $attr = isset($data['attr'])?$data['attr']:[];

        GoodsModel::beginTrans();
        try {
            GoodsModel::updateOne($data, ['goods_id' => $data['goods_id']]);
            $keySpecGoodsPrice = SpecGoodsPrice::where(['goods_id'=>$data['goods_id']])->column('key','item_id');//规格项

            //处理规格
            if(!empty($spec_item)){
                $spec = [];
                $update_spec = [];
                $item_ids = [];
                foreach($spec_item as $k=>$v){
                    if( in_array($k,$keySpecGoodsPrice)){
                        $id = array_search($k,$keySpecGoodsPrice);
                        $item_ids[] = $id;
                        $update_spec[] = [
                            'item_id'=>$id,
                            'key' => $k,
                            'key_name' => $v['key_name'],
                            'price' => $v['price'],
                            'store_count' => $v['store_count'],
                            'sku' => $v['sku'],
                            'goods_id' => $data['goods_id'],
                        ];

                        //SpecGoodsPrice::updateOne($update_spec,['goods_id' => $data['goods_id'],'key'=>$k]);
                    }else {
                        $spec[] = [
                            'key' => $k,
                            'key_name' => $v['key_name'],
                            'price' => $v['price'],
                            'store_count' => $v['store_count'],
                            'sku' => $v['sku'],
                            'goods_id' => $data['goods_id'],
                        ];
                    }
                }

                SpecGoodsPrice::whereNotIn('item_id',$item_ids)->delete();
                SpecGoodsPrice::updateAll($update_spec);
                SpecGoodsPrice::setAll($spec);
            }

            //处理属性
            if(!empty($attr)){
                $goods_attr = [];
                foreach($attr as $k=>$v){
                    $goods_attr = [
                        'goods_id'=>$data['goods_id'],
                        'attr_id'=>$k,
                        'attr_value'=>$v,
                        'attr_price'=>0,
                    ];
                    $count = GoodsAttr::getCount(['goods_id'=>$data['goods_id'],'attr_id'=>$k],'goods_attr_id');
                    if($count>0){
                        GoodsAttr::updateOne($goods_attr,['goods_id'=>$data['goods_id'],'attr_id'=>$k]);
                    }else{
                        GoodsAttr::create($goods_attr);
                    }
                    //GoodsAttr::updateOne($goods_attr,['goods_id'=>$data['goods_id'],'attr_id'=>$k]);
                }
                //GoodsAttr::setAll($goods_attr,true);
            }

            GoodsModel::commitTrans();
        } catch (\Exception $ex) {
            GoodsModel::rollbackTrans();
            return JsonService::error($ex->getMessage());
        }
        return JsonService::success();
    }

    public static function getAttrSpecInput($type_id,$goods_id=0){
        $attribute = self::getAttrSpec($type_id);

        $data = [];
        //处理属性
        $goods_attr = [];
        $goods_attr = GoodsAttr::where(['goods_id'=>$goods_id])->column('attr_value','attr_id');
        //print_r($goods_attr);die();
        $attr_html = '<tr><td colspan="2"><b>商品属性:</b></td></tr>';
        if(!empty($attribute['attribute'])) {
            foreach ($attribute['attribute'] as $k => $v) {
                $attr_html .= '<tr>';
                if ($v['attr_input_type'] == 0) {
                    $value = isset($goods_attr[$v['attr_id']])?$goods_attr[$v['attr_id']]:'';
                    $attr_html .= '<td style="width:28%">' . $v['attr_name'] . '</td><td><input type="text" class="form-control" name="attr[' . $v['attr_id'] . ']" value="'.$value.'"></td>';
                } else if ($v['attr_input_type'] == 2) {
                    $value = isset($goods_attr[$v['attr_id']])?$goods_attr[$v['attr_id']]:'';
                    $attr_html .= '<td style="width:28%">' . $v['attr_name'] . '</td><td><textarea class="form-control" name="attr[' . $v['attr_id'] . ']">'.$value.'</textarea></td>';
                } else {
                    $attr_select = '<select name="attr[' . $v['attr_id'] . ']" class="form-control">';
                    if ($v['attr_values']) {
                        $tmp_option_val = explode(PHP_EOL, $v['attr_values']);
                        foreach($tmp_option_val as $k2=>$v2){
                            $v2 = preg_replace("/\s/","",$v2);
                            //echo $v['attr_id'];
                            if(isset($goods_attr[$v['attr_id']])&&$goods_attr[$v['attr_id']] == $v2){
                                $attr_select .= '<option selected="selected" value="' . $v2 . '">' . $v2 . '</option>';
                            }else{
                                $attr_select .= '<option value="' . $v2 . '">' . $v2 . '</option>';
                            }
                        }

                        $attr_select .= '</select>';
                        $attr_html .= '<td style="width:28%">' . $v['attr_name'] . '</td><td>' . $attr_select . '</td>';
                    }
                }
                $attr_html .= '</tr>';
            }
        }

        $data['attribute'] = $attr_html;

        //处理规格
        $items_ids = [];
        if($goods_id) {
            $items_id = SpecGoodsPrice::getAll(['goods_id' => $goods_id], [], "GROUP_CONCAT(`key` SEPARATOR '_') AS items_id")->toArray();
            $items_ids = explode('_', $items_id[0]['items_id']);
        }

        $spec_html = '<tr><td colspan="2"><b>商品规格:</b></td></tr>';
        if(!empty($attribute['spec'])) {
            foreach ($attribute['spec'] as $k => $v) {
                $spec_html .= '<tr>';
                $spec_html .= '<td style="width: 8%;">' . $v['name'] . '</td>';
                $spec_item_html = '<td>';
                if (!empty($v['spec_item'])) {
                    for ($i = 0; $i < count($v['spec_item']); $i++) {
                        if(in_array($v['spec_item'][$i]['id'],$items_ids)){
                            $buttonClass = 'btn-success';
                        }else{
                            $buttonClass = 'btn-default';
                        }
                        $spec_item_html .= '<button type="button" data-spec_id="' . $v['spec_id'] . '" data-item_id="' . $v['spec_item'][$i]['id'] . '" class="btn '.$buttonClass.' btn-sm">' . $v['spec_item'][$i]['item'] . '</button>&nbsp;&nbsp;&nbsp;';
                    }
                    $spec_item_html .= '</td>';
                }
                $spec_html .= $spec_item_html;
                $spec_html .= '</tr>';
            }
        }
        $data['spec'] = $spec_html;
        return $data;
    }

    /*
     * 获取属性规格
     * */
    public static function getAttrSpec($type_id){
        //获取属性
        $attribute = GoodsAttribute::getAll(['type_id'=>$type_id],['attr_id','order'=>'desc'],'attr_id,attr_name,attr_input_type,attr_values')->each(function($item){
            if($item['attr_input_type'] == 1){
                //$item['attr_values'] = explode(PHP_EOL,$item['attr_values']);
            }
        })->toArray();
        $tmp = Spec::where(['type_id'=>$type_id])->with(['getSpecItems'])->order(['id','order'=>'desc'])->select();
        $spec = [];
        if(!empty($tmp)){
            foreach($tmp as $k=>$v){
                $item = [];
                if(!empty($v['getSpecItems'])){
                    $item = $v->getSpecItems->toArray();
                }
                $spec[] = [
                    'spec_id' => $v['id'],
                    'name'    => $v['name'],
                    'spec_item'=>$item,
                ];
            }
        }
        $data['attribute'] = $attribute;
        $data['spec'] = $spec;
        return $data;
    }

    public static function getSpecInput($goods_id, $spec_arr)
    {
        // <input name="item[2_4_7][price]" value="100" /><input name="item[2_4_7][name]" value="蓝色_S_长袖" />
        /*$spec_arr = array(
            20 => array('7','8','9'),
            10=>array('1','2'),
            1 => array('3','4'),

        );  */
        // 排序
        foreach ($spec_arr as $k => $v)
        {
            $spec_arr_sort[$k] = count($v);
        }

        asort($spec_arr_sort);
        foreach ($spec_arr_sort as $key =>$val)
        {
            $spec_arr2[$key] = $spec_arr[$key];
        }

        $clo_name = array_keys($spec_arr2);

        $spec_arr2 = combineDika($spec_arr2); //  获取 规格的 笛卡尔积

        //$spec = M('Spec')->getField('id,name'); // 规格表
        $spec = Spec::column('name','id'); // 规格表

        //$specItem = M('SpecItem')->getField('id,item,spec_id');//规格项
        $specItem = SpecItem::column('item,spec_id','id');

        //$keySpecGoodsPrice = M('SpecGoodsPrice')->where('goods_id = '.$goods_id)->getField('key,key_name,price,store_count,bar_code,sku');//规格项
        $keySpecGoodsPrice = SpecGoodsPrice::where(['goods_id'=>$goods_id])->column('key_name,price,store_count,bar_code,sku','key');//规格项
        //print_r($keySpecGoodsPrice);die();

        $str = "<table class='table table-bordered' id='spec_input_tab'>";
        $str .="<tr>";


        // 显示第一行的数据
        foreach ($clo_name as $k => $v)
        {
            $str .=" <td><b>{$spec[$v]}</b></td>";
        }
        $str .="<td><b>价格</b></td>
               <td><b>库存</b></td>
               <td><b>SKU</b></td>
             </tr>";
        // 显示第二行开始
        //print_r($spec);
        //print_r($spec_arr2);
       //print_r($specItem);
        foreach ($spec_arr2 as $k => $v)
        {
            $str .="<tr>";
            $item_key_name = array();
            foreach($v as $k2 => $v2)
            {
                $str .="<td>{$specItem[$v2]['item']}</td>";
                $item_key_name[$v2] = $spec[$specItem[$v2]['spec_id']].':'.$specItem[$v2]['item'];
                //$item_key_name[$specItem[$v2]['spec_id'].'|'.$v2] = $spec[$specItem[$v2]['spec_id']].':'.$specItem[$v2]['item'];
            }
            ksort($item_key_name);
            $item_key = implode('_', array_keys($item_key_name));
            $item_name = implode(' ', $item_key_name);

            if(!empty($keySpecGoodsPrice)) {

                $price = isset($keySpecGoodsPrice[$item_key]['price'])&&$keySpecGoodsPrice[$item_key]['price']?$keySpecGoodsPrice[$item_key]['price']:0;
                $sore_count = isset($keySpecGoodsPrice[$item_key]['store_count'])&&$keySpecGoodsPrice[$item_key]['store_count']?$keySpecGoodsPrice[$item_key]['store_count']:0;

                $sku = isset($keySpecGoodsPrice[$item_key]['sku'])&&$keySpecGoodsPrice[$item_key]['store_count']?$keySpecGoodsPrice[$item_key]['sku']:'';

                $str .= "<td><input name='item[$item_key][price]' value='{$price}' class='form-control' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")' /></td>";
                $str .= "<td><input name='item[$item_key][store_count]' class='form-control'value='{$sore_count}' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")'/></td>";
                $str .= "<td><input name='item[$item_key][sku]' class='form-control' value='{$sku}' />
                <input type='hidden' name='item[$item_key][key_name]' value='$item_name' /></td>";

            }else{
                $str .= "<td><input name='item[$item_key][price]' class='form-control' value='0' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")' /></td>";
                $str .= "<td><input name='item[$item_key][store_count]' class='form-control' value='0' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")'/></td>";
                $str .= "<td><input name='item[$item_key][sku]' class='form-control' value='' />
                <input type='hidden' name='item[$item_key][key_name]' value='$item_name' /></td>";
            }
            $str .="</tr>";
        }
        $str .= "</table>";
        return $str;
    }
}

